package com.blt.car.me;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blt.car.R;
import com.blt.car.base.BaseFragment;
import com.blt.car.base.ViewHolder;
import com.blt.car.utils.ActivityHelper;
import com.blt.car.widget.GlideCircleTransform;
import com.bumptech.glide.Glide;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import blt.app_core.api.base.CoreEvent;
import blt.app_core.api.base.CoreManager;
import blt.app_core.api.login.LoginApi;
import blt.app_core.api.login.bean.User;
import blt.app_core.api.other.OutApi;
import blt.app_core.log.Logger;
import blt.app_core.utils.UriProdiver;

import static android.app.Activity.RESULT_OK;

/**
 * Created by xgp on 2017/6/13.
 */

public class MeFragment extends BaseFragment implements View.OnClickListener {

    String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497978792896&di=fa2604c5944ef316cbcb9a03809a373a&imgtype=0&sr" +
            "c=http%3A%2F%2Fwww.nongshanghang.cn%2Fyule%2Fuploads%2Fallimg%2F170109%2F1536295K1_1.jpg";

    private Uri srcUri;
    public static final int SELECT_PIC_BY_TACK_CAMEAR = 1;
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    public static final int PHOTO_REQUEST_CUT = 3;


    private File tempFile;
    private String picPath;
    private ImageView mHead;

    private TextView mNick;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }


    @Override
    protected void initData() {
        super.initData();
        CoreManager.getCore(LoginApi.class).getUserInfo();
    }

    @Override
    protected void initView(ViewHolder holder) {
        mHead = holder.get(R.id.me_head_img);
        holder.get(R.id.me_rl_purse);
        holder.get(R.id.me_rl_bill_manegr);
        holder.get(R.id.me_rl_setting);
        holder.get(R.id.me_rl_complain);
        holder.get(R.id.me_contact_sir);
        mNick = holder.get(R.id.me_nickname);
        holder.setOnClickListener(this, R.id.me_head_img, R.id.me_rl_purse, R.id.me_rl_bill_manegr, R.id.me_nickname,
                R.id.me_rl_setting, R.id.me_rl_complain, R.id.me_contact_sir);
//        Glide.with(this).load(url).bitmapTransform(new GlideCircleTransform(getActivity())).into(mHead);
        Glide.with(this).load(R.mipmap.default_head).bitmapTransform(new GlideCircleTransform(getActivity())).into(mHead);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.me_head_img:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("修改头像");
                builder.setItems(new String[]{"相册", "拍照"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                takePhoto();
                                break;
                            case 1:
                                takeCamera();
                                break;
                        }
                    }
                });
                builder.create();
                builder.show();
                break;
            case R.id.me_nickname:
                ActivityHelper.toModifyActivity(getActivity());
                break;
            case R.id.me_rl_purse:
                ActivityHelper.toMyPurse(getActivity());
                break;
            case R.id.me_rl_complain:
                ActivityHelper.toMyComplain(getActivity());
                break;
            case R.id.me_rl_bill_manegr:
                ActivityHelper.toBillManager(getActivity());
                break;
            case R.id.me_rl_setting:
                ActivityHelper.toSettingActivity(getActivity());
                break;
            case R.id.me_contact_sir:
                AlertDialog.Builder al = new AlertDialog.Builder(getActivity());
                final String phone = "13833526874";
                al.setTitle("是否拨打客服电话：" + phone);
                al.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                al.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        call(phone);
                        dialog.dismiss();
                    }
                });
                al.create();
                al.show();
                break;

        }
    }

    /**
     * 调用拨号功能
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
        startActivity(intent);
    }

    private void takeCamera() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        tempFile = new File(Environment.getExternalStorageDirectory(),
                "temp_photo.jpg");

        // 从文件中创建uri
        Uri uri = Uri.fromFile(tempFile);
        srcUri = Uri.fromFile(tempFile);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(openCameraIntent, SELECT_PIC_BY_TACK_CAMEAR);
    }

    private void takePhoto() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, srcUri);
        pickIntent.setDataAndType(srcUri, "image/*");
        startActivityForResult(pickIntent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @CoreEvent(coreClientClass = LoginApi.class)
    public void onNickBack(String nickname) {
        mNick.setText(nickname);
    }

    @CoreEvent(coreClientClass = LoginApi.class)
    public void onUserInfo(User user) {
        String uri = url;
        if (user.icon != null) {
            uri = user.icon;
        }
        Glide.with(this).load(UriProdiver.IMAGE_BASE_URL + uri).bitmapTransform(new GlideCircleTransform(getActivity())).into(mHead);
        mNick.setText(user.loginName);
    }

    @CoreEvent(coreClientClass = OutApi.class)
    public void onUploadIcon(String url) {
        toast("修改头像成功");
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Logger.d(requestCode+"     result:"+resultCode);
//        if (resultCode == ModifyNickActivity.MODIFY_NICKNAME_SUCCESS) {
//            String nickname = data.getExtras().getString("nickname");
//            mNick.setText(nickname);
//        }
        if (resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    showHead(uri);
                } else {
                    Bundle bandle = data.getExtras();
                    if (bandle != null) {
                        Bitmap bitmap = (Bitmap) bandle.get("data");
                        if (bitmap != null) {
                            setHeadImage(bitmap);
                        }
                    } else {
                        if (srcUri != null) {
                            //showHead(tempUri);
                            picPath = tempFile.getPath();
                            picPath = srcUri.getPath();
                            Bitmap bitmap = null;//BitmapFactory.decodeFile(picPath);
                            if (picPath != null) {
                                bitmap = BitmapFactory.decodeFile(picPath);
                            }
                            crop(srcUri);
                        }
                    }
                }
            } else {

                if (tempFile != null) {
                    picPath = tempFile.getPath();
                    Bitmap bitmap = BitmapFactory.decodeFile(picPath);
                    crop(Uri.fromFile(tempFile));
                }
            }
            if (requestCode == PHOTO_REQUEST_CUT) {

                Bitmap bitmap = null;
                if (srcUri != null) {
                    picPath = srcUri.getPath();
                    if (picPath != null) {
                        bitmap = BitmapFactory.decodeFile(picPath);
                    }
                }
                if (bitmap != null) {
                    CoreManager.getCore(OutApi.class).uploadIcon(picPath);
                    setHeadImage(bitmap);
                }
            }
        }
    }


    //返回显示头像
    private void showHead(Uri uri) {
        String[] pojo = {MediaStore.MediaColumns.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            // 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
            if (Build.VERSION.SDK_INT < 14) {
                cursor.close();
            }
        } else {
            if (uri != null) {
                picPath = uri.getPath();
            }
        }
        if (picPath != null) {
            BitmapFactory.Options option = new BitmapFactory.Options();
            option.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picPath, option);

            option.inSampleSize = computeSampleSize(option, -1, 128 * 128);
            option.inJustDecodeBounds = false;
            try {
                Bitmap bm = BitmapFactory.decodeFile(picPath, option);

                String fileName = "temp.png";
                String filePath = getContext().getFilesDir().getAbsolutePath();
                File f = new File(filePath, fileName);
                int tryTimes = 5;
                while (f.exists() && tryTimes > 0) {
                    f.delete();
                    --tryTimes;
                }
                try {
                    FileOutputStream out = new FileOutputStream(f);
                    bm.compress(Bitmap.CompressFormat.PNG, 0, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                }
//                mHead.setImageBitmap(bm);
                setHeadImage(bm);
                CoreManager.getCore(OutApi.class).uploadIcon(picPath);

            } catch (OutOfMemoryError err) {
//                MLog.error(TAG, "android java.lang.OutOfMemoryError");
            } catch (NullPointerException e) {
//                MLog.error(TAG, e.toString());
            }
        }
    }

    private void setHeadImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        Glide.with(this).load(bytes).bitmapTransform(new GlideCircleTransform(getActivity())).into(mHead);

    }

    private void crop(Uri uri) {
        final int dp = 128;

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);//输出是X方向的比例
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
        intent.putExtra("outputX", dp);//输出X方向的像素
        intent.putExtra("outputY", dp);
        intent.putExtra("outputFormat", "PNG");//Bitmap.CompressFormat.JPEG.toString()
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, srcUri);
        intent.putExtra("return-data", false);//设置为不返回数据

        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) &&
                (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

}
